package com.kzd.gtgame.main.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.google.android.material.tabs.TabLayout
import com.kzd.gtgame.R
import com.kzd.gtgame.custom.setEmptyView
import com.kzd.gtgame.custom.setTransitionStatusE
import com.kzd.gtgame.custom.setTransitionStatusM
import com.kzd.gtgame.custom.setTransitionStatusT
import com.kzd.gtgame.entity.ServiceTitle
import com.kzd.gtgame.jetpack.vm.HomeViewModel
import com.kzd.gtgame.main.home.adapter.ServiceChildAdapter
import com.kzd.gtgame.main.home.adapter.ServiceGroupAdapter
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.fragment_home_service.*
import kotlinx.android.synthetic.main.include_app_refresh.*

class HomeServiceFragment : OwnerViewModeFragment<HomeViewModel>() {

    companion object {
        const val KEY_SERVICE_ACTION = "KEY_SERVICE_ACTION"
        fun newInstance(action: Int): HomeServiceFragment {
            val bundle = Bundle().apply {
                putInt(KEY_SERVICE_ACTION, action)
            }
            return HomeServiceFragment().apply {
                arguments = bundle
            }
        }
    }

    private val mAction: Int by lazy {
        arguments?.getInt(KEY_SERVICE_ACTION) ?: 0
    }

    private var mTabSelectIndex: Int = 0

    private val mTodayOnTabSelectedListener: TabLayout.OnTabSelectedListener by lazy {
        object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                rvAppRefreshBody.scrollToPosition((tab?.position ?: 0))
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) = Unit

            override fun onTabReselected(tab: TabLayout.Tab?) = Unit
        }
    }

    private val mQuickOnTabSelectedListener: TabLayout.OnTabSelectedListener by lazy {
        object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
//                val position = tab?.position ?: 0
//                if (position == 0) {
//                    return
//                }
//                mTabSelectIndex = position

                val data = viewModel.homeServiceQuickLiveData.value
                    ?.data?.data ?: return
                val key = tab?.tag?.toString()
                    ?: return
                mServiceGroupAdapter.setNewInstance(data[key])
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) = Unit

            override fun onTabReselected(tab: TabLayout.Tab?) = Unit
        }
    }

    private val mServiceGroupAdapter: ServiceGroupAdapter by lazy {
        ServiceGroupAdapter()
    }

    private val mServiceChildAdapter: ServiceChildAdapter by lazy {
        ServiceChildAdapter()
    }

    override fun viewModel(): HomeViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.fragment_home_service

    override fun initView() {
        rvAppRefreshBody.apply {
            layoutManager = LinearLayoutManager(context)
        }.adapter = if (mAction == 2) {
            mServiceChildAdapter
        } else mServiceGroupAdapter

        when (mAction) {
            1 -> tabHomeServiceKind.addOnTabSelectedListener(
                mQuickOnTabSelectedListener
            )
            2 -> tabHomeServiceKind.visibility =
                View.GONE
            else -> tabHomeServiceKind.addOnTabSelectedListener(
                mTodayOnTabSelectedListener
            )
        }

        mSmartRefreshLayout.setOnRefreshListener {
            initData()
        }
        mSmartRefreshLayout.setOnLoadMoreListener {
            viewModel.homeServiceHistory(isLoadMore = true)
        }
    }

    override fun initData() {
        when (mAction) {
            1 -> viewModel.homeServiceQuick()
            2 -> viewModel.homeServiceHistory()
            else -> viewModel.homeServiceToday()
        }
    }

//    private fun initData(isLoadMore:Boolean) {
//        when (mAction) {
//            1 -> viewModel.homeServiceQuick()
//            2 -> viewModel.homeServiceHistory(isLoadMore)
//            else -> viewModel.homeServiceToday()
//        }
//    }

    override fun initViewMode() {
        viewModel.homeServiceTodayLiveData.observe(viewLifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            response.data?.times?.let {
                fillData(it)
            }
            val data = response.data?.data
                ?: return@observe
            mServiceGroupAdapter.setNewInstance(data)
        })

        viewModel.homeServiceQuickLiveData.observe(viewLifecycleOwner, { response ->
//            if (response.status == Status.FAILURE) {
//                toast(response.error?.msg)
//            }
            setTransitionStatusM(response, mServiceGroupAdapter, mSmartRefreshLayout, (false))
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            val keys = data.keys.toMutableList()
            if (keys.isNullOrEmpty()) {
                return@observe
            }
            fillData(keys)

            val key0 = tabHomeServiceKind.getTabAt((0))
                ?.tag?.toString() ?: return@observe

            val values = data[key0]

            if (values.isNullOrEmpty()) {
                mServiceGroupAdapter.setEmptyView()
                return@observe
            }

            mServiceGroupAdapter.setNewInstance(values)

//            val title:MutableList<ServiceTitle> = mutableListOf()
//
//            for (value in data.values) {
//                title.addAll(value)
//                break
//            }
//            if (title.isNullOrEmpty()) {
//                return@observe
//            }
        })

        viewModel.homeServiceHistoryLiveData.observe(viewLifecycleOwner, { response ->
            setTransitionStatusE(response, mServiceChildAdapter, mSmartRefreshLayout)
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            val isLoadMore = response.data?.isLoadMore
                ?: return@observe
            if (isLoadMore) {
                mServiceChildAdapter.addData(data)
            } else {
                mServiceChildAdapter.setNewInstance(data)
            }
        })
    }


    private fun fillData(times: MutableList<String>) {
        tabHomeServiceKind.apply {
            removeAllTabs()
            for (item in times) addTab(newTab().apply {
                val view: View = LayoutInflater.from(requireContext())
                    .inflate(R.layout.item_game_service_label, null)
                view.findViewById<TextView>(R.id.tvGameServiceLabelName)
                    .text = item
                customView = view
                tag = item
            })
            visibility = View.VISIBLE
        }
        tabHomeServiceKind.getTabAt(mTabSelectIndex)?.select()
    }

}